import React, { useState, useEffect, useRef } from 'react';
import { Button, Table, Pagination, Switch, message, Modal, Input, Form } from 'antd';
import ContentTitle from "@/components/contentTitle/ContentTitle";
import { getGoodsTypeList, deleteGoodsType, updateGoodsType, addGoodsType } from '@/api/goods';

export default function GoodsType() {
  // 用于存储每一行的编辑状态，以 id 为键
  const [editStates, setEditStates] = useState({});
  // 用于存储编辑时开关的状态，以 id 为键
  const [switchStates, setSwitchStates] = useState({});
  const [changeCateName, setChangeCateName] = useState('');
  const [openAdd, setOpenAdd] = useState(false);
  const [cateNameInp, setCateNameInp] = useState('');
  const [stateInp, setStateInp] = useState(false);
  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '分类名',
      dataIndex: 'cateName',
      key: 'cateName',
      render: (text, record) => {
        const isEdit = editStates[record.id];
        return isEdit ? <Input style={{ color: '#1890ff' }} defaultValue={text} onChange={(e) => handleCateNameChange(e)} /> : text;
      }
    },
    {
      title: '是否启用',
      dataIndex: 'state',
      key: 'state',
      render: (text, record) => {
        const isEdit = editStates[record.id];
        const currentSwitchState = switchStates[record.id] === undefined ? (text === 1) : switchStates[record.id];
        return isEdit ?
          (
            <Switch checked={currentSwitchState}
              onChange={(checked) => handleSwitchChange(record.id, checked)} />
          ) :
          (
            text === 1 ? <Switch checked={true} disabled /> : <Switch disabled checked={false} />
          )
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => {
        const isEdit = editStates[record.id]
        return isEdit ? (
          <>
            <Button type="primary" onClick={() => handleSave(record)}>保存</Button>
            <Button type="primary" danger style={{ marginLeft: 10 }} onClick={() => handelDle(record.id)}>删除</Button>
          </>
        ) : (
          <>
            <Button type="primary" onClick={() => setEditStates({ ...editStates, [record.id]: true })}>编辑</Button>
            <Button type="primary" danger style={{ marginLeft: 10 }} onClick={() => handelDle(record.id)}>删除</Button>
          </>
        );
      }
    }
  ];

  const [data, setData] = useState([
    {
      id: null,
      cateName: '',
      state: null
    }
  ]);

  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);

  const change = (page, pageSize) => {
    setCurrentPage(page);
    setPageSize(pageSize);
  };

  const getList = async () => {
    const res = await getGoodsTypeList({ currentPage, pageSize });
    const newData = res.data.map(item => ({ ...item, key: item.id }));
    setData(newData);
    setTotal(res.total);
  };

  useEffect(() => {
    getList();
  }, [currentPage, pageSize]);

  const handleCancel = (msg) => {
    message.info(msg);
  }

  // 删除
  const ckDelete = async (id) => {
    const res = await deleteGoodsType({ id });
    if (res.code === 0) {
      message.success('删除成功');
      getList();
    } else {
      message.error('删除失败');
    }
  }
  const handelDle = (id) => {
    Modal.confirm({
      title: '删除分类提示',
      content: '确定要删除该分类吗',
      okText: '确定',
      cancelText: '取消',
      onOk: () => ckDelete(id),
      onCancel: () => handleCancel('取消删除')
    });
  }

  //
  const handleCateNameChange = (e) => {
    setChangeCateName(e.target.value);
  }
  // 处理开关状态变化
  const handleSwitchChange = (id, checked) => {
    setSwitchStates((prevStates) => ({ ...prevStates, [id]: checked }));
  };
  //保存修改
  const handleSave = async (row) => {
    const id = row.id;
    const cateName = changeCateName ? changeCateName : row.cateName; // 获取编辑后的分类名
    const state = switchStates[id] ? 1 : 0; // 获取编辑后的开关状态

    const res = await updateGoodsType({ id, cateName, state });
    if (res.code === 0) {
      message.success('保存成功');
      setChangeCateName(''); // 清空编辑后的分类名
      setSwitchStates((prevStates) => ({ ...prevStates, [id]: state })); // 更新开关状态
      setEditStates((prevStates) => ({ ...prevStates, [id]: false })); // 关闭编辑状态
      // 刷新列表
      getList();
    } else {
      message.error('保存失败');
    }
  }

  const onOk = async() => {
    const {code,msg} = await addGoodsType({cateName:cateNameInp,state:stateInp});
    if(code === 0){
      message.success(msg);
      setOpenAdd(false);
      getList();
    }else{
      message.error(msg);
    }
  }
  const handleAddCancel = () => {
    setOpenAdd(false);
  }
  return (
    <>
      <ContentTitle title="商品分类">
        <Button onClick={() => setOpenAdd(true)}>添加分类</Button>
      </ContentTitle>
      {
        data.length > 1 ?
          <>
            <Table columns={columns} dataSource={data} pagination={false} />
            <Pagination
              key={`${currentPage}-${pageSize}`}
              total={total}
              showSizeChanger
              showQuickJumper
              defaultCurrent={currentPage}
              defaultPageSize={pageSize}
              showTotal={total => `共 ${total} 条`}
              onChange={change}
              pageSizeOptions={['5', '10', '15', '20']}
              style={{ marginTop: 20 }}
            />
            {/* 添加框 */}
            <Modal title='添加分类' open={openAdd} onOk={onOk} onCancel={handleAddCancel}>
              <Form
                name="basic"
                initialValues={{ remember: false }}
                autoComplete="off"
              >
                <Form.Item label='商品分类名'>
                  <Input onChange={(e) => setCateNameInp(e.target.value)} />
                </Form.Item>
                <Form.Item label='是否启用'>
                  <Switch
                    // checked={stateInp}
                    onChange={(e) => setStateInp(e ? 1 : 0)}
                  />
                </Form.Item>
              </Form>
            </Modal>
          </>
          : <Table columns={columns} dataSource={[]} />
      }

    </>
  );
}